package com.qh.pet.service.impl;

import com.qh.basic.exception.BusinessException;
import com.qh.basic.service.IBaiduAiAuditService;
import com.qh.basic.util.*;
import com.qh.order.domain.OrderPetAcquisition;
import com.qh.order.mapper.OrderPetAcquisitionMapper;
import com.qh.org.domain.Employee;
import com.qh.org.domain.Shop;
import com.qh.org.mapper.EmployeeMapper;
import com.qh.org.mapper.ShopMapper;
import com.qh.pet.domain.SearchMasterMsg;
import com.qh.pet.domain.SearchMasterMsgAuditLog;
import com.qh.pet.dto.MsgDto;
import com.qh.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.qh.pet.mapper.SearchMasterMsgMapper;
import com.qh.pet.query.SearchMasterMsgQuery;
import com.qh.pet.service.ISearchMasterMsgService;
import com.qh.basic.service.impl.BaseServiceImpl;
import com.qh.user.domain.Logininfo;
import com.qh.user.domain.User;
import com.qh.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    /**
     * 发布寻主
     * @param msg
     * @return
     */
    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //1.先添加到数据库
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);
        //2.百度AI智能审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());
        if (boo1 && boo2){//审核通过
            //设置状态
            msg.setState(1);
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核通过");
            searchMasterMsgAuditLogMapper.save(log);
            //获取距离最近的店铺
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            if (nearestShop != null){//附近五十公里找到了店铺
                //设置店铺id
                msg.setShopId(nearestShop.getId());
                //发消息通知店铺
//                SmsUtils.sendSms(nearestShop.getTel(),"您有新的订单，请到"+msg.getAddress()+"及时处理");
                System.out.println("您有新的订单，请到"+msg.getAddress()+"及时处理");
            }else {//附近五十公里没有找到店铺
                //放入寻主池
                msg.setState(3);
                //发消息给用户
//                SmsUtils.sendSms(nearestShop.getTel(),"您附近暂时没有店铺，请等待店铺开通");
                System.out.println("您附近暂时没有店铺，请等待店铺开通");
            }
            //修改状态
            searchMasterMsgMapper.update(msg);
            //返回前端
            return new AjaxResult();

        }else {//审核不通过
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);
            //发消息给用户
//                SmsUtils.sendSms(nearestShop.getTel(),"您附近再试没有店铺，请等待店铺开通");
            System.out.println("寻主消息发布失败，请检查后重新发布");
            //3.删除该条消息
            searchMasterMsgMapper.del(msg.getId());
            return AjaxResult.me().setSuccess(false).setMsg("发布失败");
        }
    }

    /**
     * 查询用户的所有寻主消息
     * @param query
     * @param request
     * @return
     */
    @Override
    public pageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.pageQuery(query);
    }

    /**
     * 管理员查询已经完成的寻主消息
     * @param query
     * @param request
     * @return
     */
    @Override
    public pageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if (employee != null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.pageQuery(query);
    }

    /**
     * 管理员查询寻主池消息
     * @param query
     * @param request
     * @return
     */
    @Override
    public pageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);
        return super.pageQuery(query);
    }

    /**
     *管理员查询待处理的寻主消息，需要区分店铺管理员还是平台管理员
     * @param query
     * @param request
     * @return
     */
    @Override
    public pageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if (employee != null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.pageQuery(query);
    }

    /**
     * 店铺拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        //已经分配给某个店铺，店铺由于某些原因拒单
        //修改状态，将店铺id清空，放入寻主池
        searchMasterMsgMapper.reject(id);
    }

    /**
     * 店铺接单
     * @param dto
     */
    @Override
    public void accept(MsgDto dto) {
        /* 平台将寻主消息分配给这个店铺，店铺接受了，并指派人去接宠物 */
        //1.先判断订单是否存在，是否正在处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(dto.getMsgId());
        if (order !=null && order.getState()==0){//说明订单存在，有人正在处理
            throw new BusinessException("订单正在处理，请勿重复接单");
        }
        //2.生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.loadOne(dto.getMsgId());
        OrderPetAcquisition newOrder = creatOrder(msg,dto);
        orderPetAcquisitionMapper.save(newOrder);
        //3.发送短信通知店员接回宠物
//        Employee employee = employeeMapper.loadOne(dto.getHandler());
//        SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在2天内前往"+msg.getAddress()+"处理");
        System.out.println("你有新的订单，请在2天内前往"+msg.getAddress()+"处理");
    }

    /**
     * 对象转换
     * @param msg
     * @param dto
     * @return
     */
    private OrderPetAcquisition creatOrder(SearchMasterMsg msg, MsgDto dto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(dto.getNote());
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setPrice(msg.getPrice());
//        order.setState(0);//默认就是0，正在处理，待处理0
//        order.setPaytype(0);//没有。接宠物的时候才有
//        order.getPetId();//没有宠物接来之后才有
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(dto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }
}
